"""
任务 装饰器
"""

import traceback
from functools import wraps
from threading import Timer

from loguru import logger as Logger  # noqa 无法直接导入 Logger 类，只能导入 logger 实例

from my_typing import *


def delay_task(delay: float = 0) -> Callable[[CallableNone], CallableNone]:
    """
    延时任务

    Args:
        delay: 延迟执行的时间（秒），默认为 0（不延迟）
    """

    def decorator(func: CallableNone) -> CallableNone:
        @wraps(func)
        def wrapper(*args, **kwargs) -> None:
            def task():
                func(*args, **kwargs)

            timer = Timer(delay, task)
            timer.start()

        return wrapper

    return decorator


def task_exc_catcher(logger: Logger) -> Callable[[CallableAny], CallableAny]:
    """
    任务异常捕获器（一般用于异步任务、延时任务）

    Args:
        logger: 日志处理器
    """

    def decorator(func: CallableAny) -> CallableAny:
        @wraps(func)
        def wrapper(*args, **kwargs) -> Any:
            tip: str = f"[异步任务][{func.__name__}]"
            logger.info(f"{tip}[开始执行]")

            try:
                res = func(*args, **kwargs)

            except Exception as _:  # noqa: ignore[broad exception]
                res = None
                logger.error(f"{tip}[执行异常]: {traceback.format_exc()}")

            finally:
                logger.info(f"{tip}[执行完毕]")

            return res

        return wrapper

    return decorator
